package com.qindian.coupontest;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.qindian.GoodsAdapter;
import com.qindian.model.CouponModel;
import com.qindian.model.ExchangeModel;
import com.qindian.model.GoodsModel;
import com.qindian.model.GoodsTypeModel;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class GoodsListActivity extends BaseActivity implements OnRefreshLoadmoreListener,View.OnClickListener {

    private static final String KEY = "Ypj7fmVAEwyHRcIH6BoBVg3xbGidvnzk";
    private static final String AGENT_ID = "9240";
    private static final String MOBILE = "18852996181";
    private RecyclerView mRecyclerGoods;
    private SmartRefreshLayout mLayoutRefresh;
    private String mPlatform;
    private String mType;
    private String mDetail;
    private GoodsAdapter mGoodsAdapter;
    private int mPage = 1;
    private boolean mIsRefresh = true;
    private int mGap;
    private List<GoodsTypeModel> mGoodsTypeModels;
    private ImageView mImgBack;
    private TextView mTxtTitle;
    private TextView mTxtFilter;
    private String mCId;
    private DrawerLayout mDrawerLayout;
    private RecyclerView mRecyclerType;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_list);
        mRecyclerGoods = findViewById(R.id.recycler_goods);
        mLayoutRefresh = findViewById(R.id.layout_refresh);
        mImgBack=findViewById(R.id.img_back);
        mTxtTitle=findViewById(R.id.txt_title);
        mTxtFilter=findViewById(R.id.txt_filter);
        mDrawerLayout=findViewById(R.id.layout_drawer);
        mRecyclerType=findViewById(R.id.recycler_type);
        mImgBack.setOnClickListener(this);
        mTxtFilter.setOnClickListener(this);
        mPlatform = getIntent().getStringExtra("platform");
        mType = getIntent().getStringExtra("type");
        mGoodsTypeModels=new ArrayList<>();
        switch (mType) {
            case "jd":
                mTxtTitle.setText("京东优惠券");
//                mGoodsTypeModels.add(new GoodsTypeModel(null,"全部"));
                mGoodsTypeModels.add(new GoodsTypeModel("1","女装"));
                mGoodsTypeModels.add(new GoodsTypeModel("2","男装"));
                mGoodsTypeModels.add(new GoodsTypeModel("3","数码家电"));
                mGoodsTypeModels.add(new GoodsTypeModel("4","母婴玩具"));
                mGoodsTypeModels.add(new GoodsTypeModel("5","美妆个护"));
                mGoodsTypeModels.add(new GoodsTypeModel("6","食品保健"));
                mGoodsTypeModels.add(new GoodsTypeModel("7","内衣配饰"));
                mGoodsTypeModels.add(new GoodsTypeModel("12","居家生活"));
                mGoodsTypeModels.add(new GoodsTypeModel("13","鞋品箱包"));
                mGoodsTypeModels.add(new GoodsTypeModel("16","运动户外"));
                mGoodsTypeModels.add(new GoodsTypeModel("17","文体车品"));
                mGoodsTypeModels.add(new GoodsTypeModel("18","其它"));
                break;

            case "tb":
                mTxtTitle.setText("淘宝优惠券");
//                mGoodsTypeModels.add(new GoodsTypeModel(null,"全部"));
                mGoodsTypeModels.add(new GoodsTypeModel("12","女装"));
                mGoodsTypeModels.add(new GoodsTypeModel("13","男装"));
                mGoodsTypeModels.add(new GoodsTypeModel("14","内衣"));
                mGoodsTypeModels.add(new GoodsTypeModel("15","母婴"));
                mGoodsTypeModels.add(new GoodsTypeModel("16","化妆品"));
                mGoodsTypeModels.add(new GoodsTypeModel("17","居家"));
                mGoodsTypeModels.add(new GoodsTypeModel("18","鞋包配饰"));
                mGoodsTypeModels.add(new GoodsTypeModel("19","美食"));
                mGoodsTypeModels.add(new GoodsTypeModel("20","车品"));
                mGoodsTypeModels.add(new GoodsTypeModel("21","数码家电"));
                mGoodsTypeModels.add(new GoodsTypeModel("22","其它"));
                break;
        }
        mDetail = getIntent().getStringExtra("detail");
        mGap = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5f, getResources().getDisplayMetrics());

        mGoodsAdapter = new GoodsAdapter(R.layout.item_goods_coupon,mType);
        mRecyclerGoods.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerGoods.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.set(0, mGap, 0, mGap);
            }
        });
        mGoodsAdapter.bindToRecyclerView(mRecyclerGoods);
        mGoodsAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                GoodsModel.DataBean.ListBean bean = mGoodsAdapter.getData().get(position);
                exchangeCoupon(mType, bean.getId(), MOBILE);

            }
        });
        mLayoutRefresh.setOnRefreshLoadmoreListener(this);

        mRecyclerType.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerType.addItemDecoration(new DividerItemDecoration(GoodsListActivity.this,DividerItemDecoration.VERTICAL));
        GoodsTypeAdapter adapter = new GoodsTypeAdapter(R.layout.item_goods_type, mGoodsTypeModels);
        adapter.bindToRecyclerView(mRecyclerType);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mDrawerLayout.closeDrawers();
                mCId=mGoodsTypeModels.get(position).getCatId();
                mIsRefresh=true;
                showLoadingDialog();
                getGoodsList(1,mCId);

            }
        });
        mGoodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                GoodsModel.DataBean.ListBean bean=mGoodsAdapter.getData().get(position);
                String url=bean.getPlathform_url();
                switch (mType) {
                    case "tb":
                        if (checkPackage("com.taobao.taobao")) {
                            Intent tbIntent = new Intent();
                            tbIntent.setAction(Intent.ACTION_VIEW);
                            tbIntent.setData(Uri.parse(url));
                            tbIntent.setClassName("com.taobao.taobao", "com.taobao.tao.detail.activity.DetailActivity");
                            startActivity(tbIntent);
                        }else {
                            Intent webIntent = new Intent(GoodsListActivity.this, WebActivity.class);
                            webIntent.putExtra("title","商品详情");
                            webIntent.putExtra("url", url);
                            startActivity(webIntent);
                        }
                        break;
                    case "jd":
                        if (checkPackage("com.jingdong.app.mall")) {
                            String id=url.substring(url.lastIndexOf("/")+1,url.lastIndexOf(".html"));
                            Log.e("tag", "onItemClick: "+id);
                            String uri = "openapp.jdmobile://virtual?params=" +
                                    "{\"sourceValue\":\"0_productDetail_97\"," +
                                    "\"des\":\"productDetail\"," +
                                    "\"skuId\":\"" + id + "\"," +
                                    "\"category\":\"jump\"," +
                                    "\"sourceType\":\"homefloor\"}";
                            Intent jdIntent=new Intent();
                            jdIntent.setData(Uri.parse(uri));
                            startActivity(jdIntent);
                        }else {
                            Intent webIntent = new Intent(GoodsListActivity.this, WebActivity.class);
                            webIntent.putExtra("title","商品详情");
                            webIntent.putExtra("url", url);
                            startActivity(webIntent);
                        }
                        break;
                }
            }
        });
        getGoodsList(1,mCId);
    }

    /**
     * 获取优惠商品列表
     *
     * @param page 页码
     */
    private void getGoodsList(int page,String cId) {
        if (mGoodsAdapter.getData().size() == 0) {
            showLoadingDialog();
        }
        Map<String, Object> map = new HashMap<>();
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        String prefix = "agent_id=" + AGENT_ID + "&page=" + page;
        if (!TextUtils.isEmpty(cId)) {
            prefix="agent_id=" + AGENT_ID + "&cid="+cId+"&page=" + page;
            map.put("cid",cId);
        }
        String token = MD5Util.getMD5(prefix + time + KEY);

        map.put("agent_id", AGENT_ID);
        map.put("time", time);
        map.put("token", token);
        map.put("page", page);
        RetrofitHelper.createService().getGoodsList(mPlatform, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<GoodsModel>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(GoodsModel goodsModel) {
                        dismissLoadingDialog();
                        if (mIsRefresh) {
                            mPage = 1;
                            mGoodsAdapter.setNewData(goodsModel.getData().getList());
                            if (mGoodsAdapter.getData().size()>0) {
                                mRecyclerGoods.scrollToPosition(0);
                            }
                            if (goodsModel.getData().getTotal()
                                    > mGoodsAdapter.getData().size()) {
                                mLayoutRefresh.setLoadmoreFinished(false);
                            } else {
                                mLayoutRefresh.setLoadmoreFinished(true);
                            }
                        } else {
                            mGoodsAdapter.addData(goodsModel.getData().getList());
                            if (goodsModel.getData().getTotal()
                                    > mGoodsAdapter.getData().size()) {
                                mPage++;
                                mLayoutRefresh.setLoadmoreFinished(false);
                            } else {
                                mLayoutRefresh.setLoadmoreFinished(true);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        stopRefreshLoad();
                        if (e instanceof JsonSyntaxException) {
                            showToast("查询失败");
                        }else {
                            showToast("网络连接错误");

                        }
                        Log.e("tag", "onError: "+e.toString());

                    }

                    @Override
                    public void onComplete() {
                        stopRefreshLoad();
                    }
                });
    }

    private void exchangeCoupon(String type, final String gid, String mobile) {

        showLoadingDialog("正在兑换...");
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        map.put("gid", gid);
        map.put("mobile", mobile);
        map.put("agent_id", AGENT_ID);
        map.put("time", time);

        String prefix = "agent_id=" + AGENT_ID + "&gid=" + gid + "&mobile=" + mobile + "&type=" + type;
        String token = MD5Util.getMD5(prefix + time + KEY);
        map.put("token", token);

        RetrofitHelper.createService().exchangeCoupon(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ExchangeModel>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ExchangeModel exchangeModel) {
//                        switch (exchangeModel.getCode()) {
//                            case "400001":
//                            case "000000":
//                                getCoupon(gid);
////
//                                break;
//                            default:
//                                showToast(exchangeModel.getMsg());
//                                break;
//                        }
                        getCoupon(gid);
                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast(e.toString());
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onComplete() {
                        dismissLoadingDialog();
                    }
                });

    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mIsRefresh = false;
        getGoodsList(mPage + 1,mCId);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        mIsRefresh = true;
        getGoodsList(1,mCId);
    }

    private void stopRefreshLoad() {
        mLayoutRefresh.finishRefresh();
        mLayoutRefresh.finishLoadmore();

    }

    /**
     * 获取优惠券
     * @param id    商品id
     */
    private void getCoupon(String id) {
        showLoadingDialog("正在获取优惠券地址");
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        Map<String, Object> map = new HashMap<>();
        map.put("agent_id", AGENT_ID);
        map.put("time", time);
        map.put("id", id);
        String prefix = "agent_id=" + AGENT_ID + "&id=" + id;
        map.put("token", MD5Util.getMD5(prefix + time + KEY));

        RetrofitHelper.createService().getCoupon(mDetail, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())

                .subscribe(new Observer<CouponModel>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(CouponModel couponModel) {
                        if (couponModel.getCode().equals("000000")) {
                            String json=new Gson().toJson(couponModel,CouponModel.class);
                            try {
                                JSONObject object=new JSONObject(json).getJSONObject("data");
                                String url=object.getString("coupon_url");
                                switch (mDetail) {
                                    case "jddetail":
                                        Intent jdIntent = new Intent(GoodsListActivity.this, WebActivity.class);
                                        jdIntent.putExtra("url", url);
                                        jdIntent.putExtra("title","京东优惠券");
                                        startActivity(jdIntent);
                                        break;
                                    case "tbdetail":
                                        if (checkPackage("com.taobao.taobao")) {
                                            Intent tbIntent = new Intent();
                                            tbIntent.setAction(Intent.ACTION_VIEW);
                                            tbIntent.setData(Uri.parse(url));
                                            tbIntent.setClassName("com.taobao.taobao", "com.taobao.browser.BrowserActivity");
                                            startActivity(tbIntent);
                                        }else {
                                            showToast("请先安装手机淘宝APP");
                                        }

                                        break;
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        } else {
                            showToast(couponModel.getMsg());
                        }
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast(e.toString());
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private boolean checkPackage(String packageName){
        PackageManager manager=getPackageManager();
        List<PackageInfo> packages=manager.getInstalledPackages(0);
        for (PackageInfo info : packages) {
            if (info.packageName.equals(packageName)) {
                return true;
            }
        }
        return false;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                onBackPressed();
                break;
            case R.id.txt_filter:
                mDrawerLayout.openDrawer(Gravity.END);
                break;
        }
    }
}
